package com.mlan.userap.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import com.mlan.userap.untils.ScreenUtil;

public class CenteredImageSpan extends ImageSpan {
    public CenteredImageSpan(Context context, Bitmap bitmap) {
        super(context, bitmap);
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        Drawable d = getDrawable();
        Rect rect = d.getBounds();
        if (fm != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.descent - fmPaint.ascent; // 文字高度
            int drHeight = rect.bottom - rect.top; // 图片高度
            int top = drHeight / 2 - fontHeight / 2;
            int bottom = drHeight / 2 + fontHeight / 2;

            fm.ascent = -bottom;
            fm.descent = top;
            fm.top = -bottom;
            fm.bottom = top;
        }
        return rect.right;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        Drawable d = getDrawable();
        Rect rect = d.getBounds();
        canvas.save();
        int drawableHeight= d.getBounds().height();
        int transY  = (bottom - top - drawableHeight) / 2 + top+ScreenUtil.dpToPx(2);
       // Paint.FontMetricsInt fm = paint.getFontMetricsInt();
       // int transY = y + (fm.descent + fm.ascent) / 2 - d.getBounds().height() / 2; // 居中计算


//        // 如果没有文字，居中对齐
//        String textWithoutEmojis = text.toString().replaceAll("\\[(\\S+?)\\]", "").trim();
//        if (textWithoutEmojis.isEmpty()) {
//            transY = (bottom - top - drawableHeight) / 2 + top;
//        } else {
//            transY = y + (fontHeight - drawableHeight) / 2 + fm.ascent;
//        }
//

        canvas.translate(x, transY);
        d.draw(canvas);
        canvas.restore();
    }
}